package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.model.entity.BrowsingHistory;
import com.atguigu.lease.web.app.mapper.BrowsingHistoryMapper;
import com.atguigu.lease.web.app.service.BrowsingHistoryService;
import com.atguigu.lease.web.app.vo.history.HistoryItemVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author gqs
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {
    @Autowired
    private BrowsingHistoryMapper browsingHistoryMapper;
    @Override
    public IPage<HistoryItemVo> pageHistoryItemByUserId(IPage<HistoryItemVo> page, Long userId) {
        IPage<HistoryItemVo> historyItemVoIPage = browsingHistoryMapper.pageHistoryItemByUserId(page, userId);
        return historyItemVoIPage;
    }

    @Override
    @Async
    public void saveHistory(Long userId, Long roomId) {
        // 创建一个新的浏览历史记录实例
        BrowsingHistory browsingHistory = new BrowsingHistory();
        // 设置用户ID
        browsingHistory.setUserId(userId);
        // 设置房间ID
        browsingHistory.setRoomId(roomId);
        // 设置浏览时间
        browsingHistory.setBrowseTime(new Date());

        // 查询当前用户和房间的浏览历史记录数量
        Long count = browsingHistoryMapper.selectCount(Wrappers.lambdaQuery(BrowsingHistory.class)
                .eq(BrowsingHistory::getUserId, userId)
                .eq(BrowsingHistory::getRoomId, roomId));

        // 判断是否存在相同的浏览历史记录
        if (count > 0){
            // 如果存在，更新现有的浏览历史记录
            browsingHistoryMapper.update(browsingHistory, Wrappers.lambdaUpdate(BrowsingHistory.class)
                    .eq(BrowsingHistory::getUserId, userId)
                    .eq(BrowsingHistory::getRoomId, roomId));
        }else {
            // 如果不存在，插入新的浏览历史记录
            browsingHistoryMapper.insert(browsingHistory);
        }
    }
}